package com.mfm.servlet;


import com.mfm.bean.Users;
import com.mfm.service.UsersService;
import com.mfm.service.impl.UsersServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(value = "/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        UsersService usersService = new UsersServiceImpl();
        Users login = usersService.login(username, password);

        if (login == null){
            //以弹窗的方式提醒用户，登录失败
            //解决乱码问题
            resp.setContentType("text/html; charset=UTF-8");

            PrintWriter writer = resp.getWriter();
            writer.print("<script>location.href='login.jsp';alert('用户名或密码错误');</script>");
        }else {
            //保存用户信息
            req.getSession().setAttribute("login",login);
            //跳转页面
            resp.sendRedirect("index.jsp");
        }
    }
}
